// const apiHost ="https://cib.cigage.com:444/mzt/f"; // 测试
const apiHost = "https://fzxsh.cib.com.cn/mzt/f"; // 生产
// const apiHost = "http://192.168.31.28:8089/mzt/f";
const app = getApp();
const imgPath = "https://xqt.cib.com.cn/cib/cashServiceImages/wechatImages"
// const apiHost="https://xqt.cib.com.cn/xqt-api" 
// const imgHost="https://xqt.cib.com.cn/"

/**
 *   20211207 新封装登录
 */

/**
 * @description  匿名登录 登录先获取code,再获取匿名userInfo,一起打包给用户登录接口
 */
function anonymousLogin() {
  return _wxCode().then(_getUserInfo).then(_anonymousLoginServer).catch(err=>{
    console.log(err)
  });
}

//获取code
function _wxCode() {
  return new Promise(function (resolve, reject) {
    wx.login({
      success: function (res) {
        if (res.code) {
          console.log("wx.login success: {}", res);
          resolve(res.code);
        } else {
          reject(res);
        }
      },
      fail: function (err) {
        reject(err);
      }
    });
  });
}


/**
 * 获取用户信息，然后将_wxCode的结果与wx.getUserInfo的结果打包给_loginServer
 */
function _getUserInfo(res) {
  return new Promise(function (resolve, reject) {
    wx.getUserInfo({
      withCredentials: true,
      lang: 'zh_CN',
      success: function (userInfo) {
        var encryptedData = userInfo.encryptedData;
        var iv = userInfo.iv
        var code = res;
        resolve({
          code,
          encryptedData,
          iv
        });
      },
      fail: function (userInfo) {
        resolve({
          res
        });
      }
    });
  });
}

// 匿名登录获取token
function _anonymousLoginServer(resPackage) {
  let entryWay = "";
  let recommendId = "";
  if (app.globalData.entryWay) {
    entryWay = app.globalData.entryWay;
  }
  if (app.globalData.recommendId) {
    recommendId = app.globalData.recommendId;
  }
  let loginUrl = apiHost + "/smsk/wechat/auth/login";
  let {
    code,
    encryptedData,
    iv
  } = resPackage;
  return new Promise(function (resolve, reject) {
    wx.request({
      url: loginUrl,
      method: "POST",
      header: {
        'Content-Type': 'application/json'
      },
      data: {
        code,
        encryptedData,
        iv,
        entryWay,
        recommendId
      },
      success: function (res) {
        if (res.statusCode == 200 && res.data.code == 0) {
          wx.setStorageSync('token', res.data.data.token);
          wx.setStorageSync('userInfo', res.data.data);
          console.log("token",res.data.data.token);
          resolve(res);
        } else {
          console.warn('In _loginServer(): http statusCode error: {}', res);
          wx.showToast({
            title: '登录失败',
            icon: 'none'
          });
          reject(res);
        }
      },
      fail: function (res) {
        console.error('In _loginServer(): wx.request error: {}', res);
        wx.showToast({
          title: '登录失败',
          icon: 'none'
        });
        reject(res);
      }
    });
  });
}

/**
 * @description wx.request 封装，封装用户登录逻辑
 * @param method 请求方式 GET | POST | DELETE | PUT | PATCH
 * @param url 请求url
 * @param data 请求携带数据
 */
function request(url, method, data = {}) {
  // let token = wx.getStorageSync('token');
  // let userInfo = wx.getStorageSync('userInfo');
  return _request(url, method, data);
}


function _request(url, method, data = {}) {
  return new Promise(function (resolve, reject) {
    wx.request({
      url: apiHost + url,
      data: data,
      method: method,
      header: {
        'Content-Type': 'application/json',
        'X-Token': wx.getStorageSync('token')
      },
      success: function (res) {
        if (res.data.code == 8) {
          // token expired 会话失效
          anonymousLogin().then(function () {
            console.log('successLogin')
            _request(url, method, data).then(res => {
              console.log('_requestsuccess')
              resolve(res);
            })
          });
        } else if (res.data.code == 4) {
          wx.showToast({
            title: '登录超时，请重新登录',
            icon:'none'
          })
          wx.setStorageSync('userInfo', '');
          setTimeout(() => {
            wx.redirectTo({
              url: '/pages/cashService/roleSelection/roleSelection',
            })
          }, 1500);
        } else {
          resolve(res);
        }
      },
      fail: function (err) {
        console.error("In _request(): wx.request failed {}", err);
        reject('wx.request failed');
      }
    });
  });
}

module.exports = {
  request: request,
  imgPath: imgPath,
  //  apiHost:apiHost,
  //  imgHost:imgHost,
  anonymousLogin: anonymousLogin
}
